import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (menus: any[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];

  menus.filter((router: any) => {
    const nodeRoute: any = {};
    const keys = ["path", "children", "component", "redirect"];
    for (const key in router.data) {
      if (keys.includes(key)) {
        nodeRoute[key] = router.data[key];
      }
    }
    const data = router.data;
    if (data.component) {
      if (data.component?.toString() === "Layout") {
        // Layout组件特殊处理
        nodeRoute.component = Layout;
      } else {
        const component = modules[`../../views/${data.component}.vue`];
        if (component) {
          nodeRoute.component = component;
        } else {
          nodeRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }
    } else {
      nodeRoute.component = Layout;
    }
    nodeRoute.meta = {
      title: data.name,
      icon: data.icon,
      code: data.code,
      affix: false,
      hidden: data.hidden,
      keepAlive: data.cache,
      showSideBar: data.sideBar,
    };
    nodeRoute.name = data.code;

    if (router.children && router.children.length) {
      nodeRoute.children = filterAsyncRoutes(router.children);
    } else {
      nodeRoute.children = [];
    }
    asyncRoutes.push(nodeRoute);
  });

  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  // state
  const routes = ref<RouteRecordRaw[]>([]);
  const hasInitRoute = ref(false);

  // actions
  function setRoutes(newRoutes: RouteRecordRaw[]) {
    routes.value = constantRoutes.concat(newRoutes);
    hasInitRoute.value = true;
  }

  function hasInit(): boolean {
    return hasInitRoute.value;
  }

  /**
   * 生成动态路由
   *
   * @param menus 用户角色集合
   * @returns
   */
  function generateRoutes(menus: any[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 接口获取所有路由
      const accessedRoutes = filterAsyncRoutes(menus || []);
      setRoutes(accessedRoutes);
      resolve(accessedRoutes);
    });
  }

  /**
   * 获取与激活的顶部菜单项相关的混合模式左侧菜单集合
   */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);
  function setMixLeftMenus(topMenuPath: string): any {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (!matchedItem) {
      return;
    }

    const redirect = matchedItem.redirect;
    const children = matchedItem.children;
    if (children) {
      if (redirect) {
        const path = String(redirect);
        const child = children.find((item) =>
          topMenuPath.concat(item.path).startsWith(path)
        );
        if (child) {
          if (child.children) {
            mixLeftMenus.value = child.children;
          }

          mixLeftMenus.value = [child];
        }
      }
      if (children.length) {
        mixLeftMenus.value = children;
      } else {
        mixLeftMenus.value = [matchedItem];
      }
    } else {
      mixLeftMenus.value = [matchedItem];
    }
  }

  function clear() {
    routes.value = [];
    hasInitRoute.value = false;
  }

  return {
    routes,
    setRoutes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
    hasInit,
    clear,
  };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
